<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js对象之序列化</title>
</head>
<body>
  <ul>
    <li>JSON作为前后端交互的数据媒体，使用JSON.stringify()将对象/数组转化为JSON字符串,使用JSON.parse()将JSON字符串转化为对象/数组</li>
    <li>可在对象内部自定义toJSON返回需要被序列化的字段</li>
    <li>可使用JSON.stringify(obj, props, tabs)定制需要显示的属性和格式</li>
    <li>可使用JSON.parse(str,func)将转化后的对象再次进行处理</li>
  </ul>
  <script>
    const user = {
      name: 'Miracle',
      age: 35,
      skills: ['js', 'es', 'ts'],
      toJSON() {
        return {
          name: this.name,
          age: this.age
        }
      }
    }
    const json = JSON.stringify(user)
    console.log(json)                                         // {"name":"Miracle","age":35}
    const formatJson = JSON.stringify(user, ['name', 'age'], 2)
    // {
    //   "name": "Miracle",
    //   "age": 35
    // }
    console.log(formatJson)
    console.log(JSON.parse(json))                             // {name: "Miracle", age: 35}
    console.log(JSON.parse(json, (key, val) => {              // {name: "Miracle He", age: 35}
      if (key === 'name') {
        val += ' He'
      }
      return val
    }))
  </script>
</body>
</html>
